<?php

class Silk_Zgb_Model_Cron 
{
	public function toLocalDate($date)
	{
		return date('Y-m-d H:i:s',strtotime($date)+3600*8);
	}

	public function cacheAllOrder()
	{
		//$order = Mage::getModel('zgb/order')->load(3387,'entity_id');
		$timestamp = time()-86400*2+3600*8;
		$startDate = date("Y-m-d H:i:s",$timestamp);
		$orders = Mage::getModel('sales/order')
			->getCollection()
			->addFieldToSelect('entity_id')
			->addFieldToFilter('updated_at', array('from' => $startDate))
			->setOrder('updated_at','ASC');
			//->addFieldToFilter('status', array('nin'=>array('complete')));
			
		echo "total:".count($orders)."\r\n";
		$ids = array();
		foreach($orders as $order)
		{
			$ids[] = $order->getId();
		}
		$orders = null;
		unset($orders);
		foreach($ids as $id)
		{
			echo $id."\n";
			$this->cacheOrder($id);
		}
	}

	public function cacheOrder($id)
	{
		$order = Mage::getModel('sales/order')->load($id);
		$o = Mage::getModel('zgb/order')->load($order->getId(),'entity_id');
		//缓存表中已经是完成状态的订单跳过处理
		//if($o && $o->getId() && $o->getStatus()=='complete')
		//{
		//	echo "Skip\n";
		//}
		//else
		//{
			if(!$o->getId()) {
				$o->setEntityId($order->getId());
			}
			$o->setIncrementId($order->getIncrementId());
			$o->setState($order->getState());
			$o->setStatus($order->getStatus());
			$o->setStoreId($order->getStoreId());
			$websiteId = Mage::getModel("core/store")->load($order->getStoreId())->getWebsiteId();
			$website = Mage::getModel('core/website')->load($websiteId);
			$o->setWebsiteId($website->getId());
			$o->setWebsiteName($website->getName());
			$o->setCustomerId($order->getCustomerId());
			$o->setGrandTotal($order->getGrandTotal());
			$o->setSubtotal($order->getSubtotal());
			$o->setIsSalt($this->hasSalt($order));
			$saltTotal = $this->calcSaltTotal($order);
			$o->setGrandTotalEx($order->getGrandTotal()-$saltTotal);
			$o->setSubtotalEx($order->getSubtotal()-$saltTotal);
			$o->setAddress($order->getShippingAddress()->format("oneline"));

			//首单处理
			$collection = Mage::getModel('sales/order')->getCollection()
				->addFieldToFilter('created_at',array('lt'=>$order->getCreatedAt()))
				->addFieldToFilter('customer_id',array('eq'=>$order->getCustomerId()))
				->addFieldToFilter('status', array('nin'=>array('canceled','closed')));
			if($collection->count())
			{
				$o->setIsFirst(0);
			}
			else
			{
				$o->setIsFirst(1);
			}
			$collection = null;
			unset($collection);
			$o->setQuoteId($order->getQuoteId());
			$warehouse = Mage::getModel('zgb/warehouse')->load($order->getWarehouseId());
			$o->setWarehouseId($order->getWarehouseId());
			$o->setWarehouse($warehouse->getName());
			$dealer = Mage::getModel('zgb/dealer')->load($warehouse->getDealerId());
			$o->setDealerId($dealer->getId());
			$o->setDealer($dealer->getName());
			$o->setTotalItemCount($order->getTotalItemCount());
			$o->setCreatedAt($this->toLocalDate($order->getCreatedAt()));
			$o->save();
			// if($o->getIsSalt()){
			// 	echo "oid".$o->getId();
			// 	exit();
			// }
			$warehouse = null;
			$dealer = null;
			$website = null;
			unset($warehouse);
			unset($dealer);
			unset($website);
			echo $order->getId().$order->getCreatedAt()."\n";
		//}
		$order = null;
		unset($order);
		$o=null;
		unset($o);
	}

	public function hasSalt($order)
	{
		$items = Mage::getModel('sales/order_item')->getCollection()
				->addFieldToSelect(array('product_id','price','qty_ordered'))
				->addFieldToFilter('order_id',array('eq'=>$order->getId()));

		foreach($items as $item)
		{
			echo "item test{$item->getOrderId()}\n";
			$product = Mage::getModel('catalog/product')->load($item->getProductId());
			if($product->getIsSalt())
			{
				$items = null;
				$item =null;
				$product = null;
				unset($item);
				unset($product);
				unset($items);
				return 1;
			}
			$item =null;
			$product = null;
			unset($item);
			unset($product);
		}
		$items = null;
		unset($items);
		return 0;
	}

	public function calcSaltTotal($order)
	{
		//$items = $order->getAllItems();
		$items = Mage::getModel('sales/order_item')->getCollection()
				->addFieldToSelect(array('product_id','price','qty_ordered'))
				->addFieldToFilter('order_id',array('eq'=>$order->getId()));
		$saltTotal = 0;
		foreach($items as $item)
		{
			echo "item test{$item->getOrderId()}\n";
			$product = Mage::getModel('catalog/product')->load($item->getProductId());
			if($product->getIsSalt())
			{
				$saltTotal+=($item->getPrice()*$item->getQtyOrdered());
			}
			$item =null;
			$product = null;
			unset($item);
			unset($product);
		}
		$items = null;
		unset($items);
		return $saltTotal;
	}

	public function cacheAllOrderItem()
	{
		$sql = "SELECT MAX(item_id) FROM zgb_order_item";
		$resource = Mage::getSingleton('core/resource');
		$db = $resource->getConnection('core_read');
		$query = $db->query($sql);
		$maxItemId = $query->fetchColumn();
		$query = null;
		$db = null;

		echo "Last Item Id: {$maxItemId}\r\n";

		$items = Mage::getModel('sales/order_item')
			->getCollection()
			->addFieldToSelect('item_id')
			->addFieldToFilter('item_id', array('gt' => $maxItemId))
			->setOrder('item_id','ASC');
		$ids = array();
		foreach($items as $item)
		{
			$ids[] = $item->getId();
		}
		$items = null;
		unset($items);
		foreach($ids as $id)
		{
			$item = Mage::getModel('sales/order_item')->load($id);
			$oitem = Mage::getModel('zgb/order_item')->load($item->getId(),'item_id');
			if($oitem && $oitem->getId())
			{
				echo "Skip\n";
			}
			else
			{
				
				$oitem->setItemId($item->getId());
				$oitem->setOrderId($item->getOrderId());
				$oitem->setCreatedAt($this->toLocalDate($item->getCreatedAt()));
				$oitem->setProductId($item->getProductId());
				$oitem->setSku($item->getSku());
				$oitem->setName($item->getName());
				$oitem->setQty($item->getQtyOrdered());
				$oitem->setPrice($item->getPrice());
				$oitem->setRowTotal($item->getRowTotal());
				$oitem->setRowInvoiced($item->getRowInvoiced());
				$product = Mage::getModel('catalog/product')->setStoreId($item->getStoreId())->load($item->getProductId());
				if($product && $product->getId())
				{
					$oitem->setIsSalt($product->getIsSalt());
					$oitem->setUnit($product->getAttributeText('unit'));
					$oitem->setUnitId($product->getUnit());
					$oitem->setBrand($product->getAttributeText('brand'));
					$oitem->setBrandId($product->getBrand());
					$oitem->save();
				}
				$product = null;
				unset($product);
				echo "Item:{$item->getId()}\n";
			}
		}
	}

	/*
		13968
		63135
		63133
	*/
	public function cacheAllCustomer()
	{
		$customers = Mage::getModel('customer/customer')->getCollection()->addAttributeToSelect('entity_id')->setOrder('entity_id','ASC');
		$ids = array();
		foreach($customers as $customer)
		{
			$ids[] = $customer->getId();
		}
		$customers = null;
		unset($customers);
		foreach($ids as $id)
		{
			$customer = Mage::getModel('customer/customer')->load($id);
			$store = Mage::getModel('zgb/store')->load($customer->getId(),'entity_id');
			//if($store && $store->getId())
			//{
			//	echo "Skip\n";
			//}
			//else
			//{
				$store->setEntityId($customer->getId());
				$store->setWebsiteId($customer->getWebsiteId());
				$website = Mage::getModel('core/website')->load($customer->getWebsiteId());
				$store->setWebsiteName($website->getName());
				//$store->setUsername($customer->getUsername());
				$store->setName($customer->getFirstname());
				$store->setStoreName($customer->getLastname());
				$store->setMobile($customer->getMobile());
				$store->setCreatedAt($this->toLocalDate($customer->getCreatedAt()));
				$store->setIsActive($customer->getConfirmation()?0:1);

				// if($store->getFirstOrderAt())
				// {

				// }

				$orders = Mage::getModel('sales/order')
					->getCollection()
					->addFieldToFilter('customer_id', array('eq'=>$customer->getId()))
					->addFieldToFilter('status', array('in'=>array('complete','complete_order')));
				if($orders->count())
				{
					$orders->setOrder('created_at','ASC');

					$firstOrder = $orders->getFirstItem();
					$store->setFirstOrderAt($this->toLocalDate($firstOrder->getCreatedAt()));
					$historys = Mage::getResourceModel('sales/order_status_history_collection')->setOrderFilter($firstOrder)
						->addFieldToFilter('status', array('in'=>array('complete','complete_order')))->setOrder('created_at','desc');
					if($historys->count())
					{
						$store->setFirstOrderCompleteAt($this->toLocalDate($historys->getFirstItem()->getCreatedAt()));
					}

					$lastOrder = $orders->getLastItem();
					$store->setLastOrderAt($this->toLocalDate($lastOrder->getCreatedAt()));
					$historys = Mage::getResourceModel('sales/order_status_history_collection')->setOrderFilter($lastOrder)
						->addFieldToFilter('status', array('in'=>array('complete','complete_order')))->setOrder('created_at','desc');
					if($historys->count())
					{
						$store->setLastOrderCompleteAt($this->toLocalDate($historys->getFirstItem()->getCreatedAt()));
					}

					$now = $this->toLocalDate(date("Y-m-d H:i:s"));
					$start = $this->toLocalDate(date("Y-m-d H:i:s",time()-30*86400));
				}
				$orders = null;
				unset($orders);
				//每天更新客户信息，并且统计客户的登记
				$now = $this->toLocalDate(date("Y-m-d H:i:s"));
				$start = $this->toLocalDate(date("Y-m-d H:i:s",time()-30*86400));

				$orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('created_at',array(
					'from'=>$start,
					'to'=>$now,
					'date'=>true
				))->addFieldToFilter('status',array('in'=>array('complete','complete_order')))->addFieldToFilter('customer_id',array('eq'=>$customer->getId()));
				$star = 0;
				echo $orders->count()."\r\n";
				if($orders->count())
				{
					if($orders->count()>=4)
					{
						$total = 0;
						$skus = 0;
						foreach($orders as $order)
						{
							$total += $order->getSubtotal();
							$skus += $order->getTotalItemCount();
						}
						if($total>=1000 && $skus>=5)
						{
							$star = 3;
						}
						else
						{
							$star = 2;
						}
					}
					else
					{

						$star = 2;
					}
				}
				else
				{
					$orders = Mage::getModel('sales/order')->getCollection()
					->addFieldToFilter('status',array('in'=>array('complete','complete_order')))
					->addFieldToFilter('customer_id',array('eq'=>$customer->getId()));
					if($orders->count())
					{
						$star = 1;
					} else {
						$star = 0;
					}
				}

				$store->setStar($star);

				$store->save();
				$orders = null;
				unset($orders);
				echo $customer->getId()."\n";
			//}
			$customer = null;
			unset($customer);
		}
	}
}